# -*- coding: UTF-8 -*-
################################################################################
#
# Copyright (c) 2018 Baidu.com, Inc. All Rights Reserved
#
################################################################################
"""
本文件实现了一个完整的demo
"""


from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from bottle import route, run, template, request
from PIL import Image, ImageFont, ImageDraw


import multiprocessing
import requests
import sys
import base64
import urllib.parse
import numpy as np
import cv2
import logging
import json

import BaiduAI.EasyEdge as edge

edge.Log.set_level(logging.INFO)
edge.set_auth_license_key("936F-DA25-B0CD-DC1D")

try:
    _model_dir = '/root/baidu/v5/RES/'
    line_color = (125, 175, 75)

    pred = edge.Program()

    pred.init(model_dir=_model_dir, device=edge.Device.GPU, engine=edge.Engine.TENSORRT)
except Exception as e:
    print(e)
    exit(-1)




@route('/hello',  method='POST')
def test2():
    try:
        filename = request.forms.get('filename')
        outputFilepath = request.forms.get('outputFilepath')
        imgfilepath = "/root/baidu/img/" + outputFilepath
        # urllib2.urlretrieve(filename, imgfilepath)

        r = requests.get(filename)
        with open(imgfilepath, "wb") as code:
            code.write(r.content)

        img = cv2.imread(imgfilepath)
        h, w, _ = img.shape
        res = pred.infer_image(img, 0.63)
        for r in res:
            print(r)

        resjson=json.dumps(res)

        print(resjson)

        result = '{"h":' + str(h) + ',"w":' + str(w) + ',"res":' + resjson + '}'
        return result
    except Exception as e:
        print(e)
        return "fail"


run(host='192.168.16.4', port=80)

